package com.platform.cdcs.fragment.custom;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.fragment.TicketRelationFragment;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.InvoiceList;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.PriceItem;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.model.RefershEvent;
import com.platform.cdcs.tool.Constant;
import com.platform.cdcs.tool.FragmentUtil;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;

/**
 * Created by holytang on 2017/12/29.
 */
public class EditPriceNumFragment extends BaseFragment {

    private EditText numET;
    private ItemAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    @Override
    public void initView(View view) {
        setTitle("编辑价格和数量");
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        initLoadImg(view.findViewById(R.id.load));
        TextView cancelBtn = (TextView) view.findViewById(R.id.button1);
        cancelBtn.setText("取消");
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        TextView okBtn = (TextView) view.findViewById(R.id.button2);
        okBtn.setText("确定");
        okBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                post();
            }
        });
        numET = (EditText) view.findViewById(R.id.num);
        GridView gridView = (GridView) view.findViewById(R.id.ics_listView);
        adapter = new ItemAdapter(getContext());
        gridView.setAdapter(adapter);
        view.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Bundle bundle = getArguments();
                FragmentUtil.navigateToInNewActivity(getActivity(), AddPriceFragment.class, bundle);
            }
        });
        requestPriceList();
    }

    private void requestPriceList() {
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("itemCode", getArguments().getString("itemCode"));
        map.put("cusCode", getArguments().getString("cusCode"));
        getHttpClient().post().url(Constant.PRICE_LIST).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                dismissLoadImg();
                Type type = new TypeToken<BaseObjResponse<PriceItem.PriceList>>() {
                }.getType();
                BaseObjResponse<PriceItem.PriceList> response = new Gson().fromJson(s, type);
                if ("1".equals(response.getResult().getCode())) {
                    adapter.addAll(response.getResult().getInvoicePriceList());
                    adapter.notifyDataSetChanged();
                } else {
                    Utils.showToast(getContext(), response.getResult().getMsg());
                }
            }
        });
    }

    @Override
    public int layoutId() {
        return R.layout.edit_ticket_num;
    }

    @Subscribe
    public void onEventMainThread(RefershEvent event) {
        if (event.mclass == getClass()) {
            Utils.showToast(getContext(), "价格添加成功!");
            adapter.addItem((PriceItem) event.bundle.getSerializable("price"));
            adapter.notifyDataSetChanged();
        }
    }

    private void post() {
        if (TextUtils.isEmpty(numET.getText().toString().trim())) {
            Utils.showToast(getContext(), "数量不能为空!");
            return;
        }
        String uomPrice="";
        for(int i=0;i<adapter.getCount();i++){
            PriceItem item=adapter.getItem(i);
            if(item.isChoose()){
                uomPrice=item.getPrice();
                break;
            }
        }
        if(TextUtils.isEmpty(uomPrice)){
            Utils.showToast(getContext(), "价格不能为空");
            return;
        }
        showLoadImg();
        Map<String, String> map = new HashMap<>();
        map.put("inId", getArguments().getString("pid"));
        map.put("qty", numET.getText().toString().trim());
        map.put("uomPrice",uomPrice);
        getHttpClient().post().url(Constant.EDIT_INVOICE_PRODUCTFORAPP).params(Constant.makeParam(map)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<MockObj>>() {
                    }.getType();
                    BaseObjResponse<MockObj> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        Utils.showToast(getContext(), "数量设置成功");
                        RefershEvent event = new RefershEvent();
                        event.mclass = TicketRelationFragment.class;
                        EventBus.getDefault().post(event);
                        getActivity().finish();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private class ItemAdapter extends EnhancedAdapter<PriceItem> {

        private View.OnClickListener checkListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adapter.unCheck();
                PriceItem item = (PriceItem) view.getTag();
                item.setChoose(true);
                adapter.notifyDataSetChanged();
            }
        };

        public ItemAdapter(Context context) {
            super(context);
        }

        private void unCheck() {
            for(PriceItem item:dataList){
                item.setChoose(false);
            }
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            ViewHolder holder = (ViewHolder) paramView.getTag();
            PriceItem item = getItem(position);
            holder.titleView.setText(item.getPrice());
            holder.timeView.setText(item.getInUom());
            holder.textView.setText("换算成强生最小单位为  " + item.getUomPrice());
            holder.checkView.setSelected(item.isChoose());
            holder.checkView.setTag(item);
        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = inflater.inflate(R.layout.four_item, viewgroup, false);
            ViewHolder holder = new ViewHolder();
            holder.titleView = (TextView) rootView.findViewById(R.id.title);
            holder.titleView.getPaint().setFakeBoldText(true);
            holder.timeView = (TextView) rootView.findViewById(R.id.time);
            holder.textView = (TextView) rootView.findViewById(R.id.text);
            holder.textView.setSingleLine(false);
            holder.checkView = (ImageView) rootView.findViewById(R.id.img);
            holder.checkView.setVisibility(View.VISIBLE);
            holder.checkView.setOnClickListener(checkListener);
            holder.checkView.setBackgroundResource(R.drawable.icon_check);
            rootView.setTag(holder);
            return rootView;
        }

    }

    private class ViewHolder {
        TextView titleView, timeView, textView;
        ImageView checkView;
    }

}